package j_j_d;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class EnUi {
public  String aseEncrypt(String plainString,String key){
    String cipherString=null;
    if(key.length()!=16&&key.length()!=24&&key.length()!=32)
    {
        System.out.println("加密密钥长度");
        return cipherString;
    }
    try{

String algorithm="AES";
//创建密钥规范
        SecretKeySpec keySpec=new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8),algorithm);
    //获取Cipher对象实例
        Cipher cipher=Cipher.getInstance(algorithm+"/ECB/PKCS5Padding");
    //初始化Cipher为加密模式
        cipher.init(Cipher.ENCRYPT_MODE,keySpec);
        byte[] cipherBytes=cipher.doFinal(plainString.getBytes(StandardCharsets.UTF_8));
        cipherString= Base64.getEncoder().encodeToString(cipherBytes);

    }
catch (Exception e){
        e.printStackTrace();
}
return cipherString;
}





    public  String aseDecrypt(String cipherString,String key) {
        String plainString=null;
        if (key.length() != 16 && key.length() != 24 && key.length() != 32) {
            System.out.println("加密密钥长度");
            return plainString;
        }
        try {

            String algorithm = "AES";
//创建密钥规范
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), algorithm);
            //获取Cipher对象实例
            Cipher cipher = Cipher.getInstance(algorithm + "/ECB/PKCS5Padding");
            //初始化Cipher为加密模式
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            byte[] cipherBytes = cipher.doFinal(Base64.getDecoder().decode(cipherString));
            plainString = new String(cipherBytes);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return plainString;
    }



}
